package com.sms.platform.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sms.platform.common.constants.RabbitMqConsants;
import com.sms.platform.common.model.Standard_Report;
import com.sms.platform.common.model.Standard_Submit;
import com.sms.platform.feign.CacheService;
import com.sms.platform.mq.SmsSender;
import com.sms.platform.service.QueueService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @author xjh
 * @date 2020-08-11
 */
@Service
@Slf4j
public class QueueServiceImpl implements QueueService {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SmsSender smsSender;

    @Autowired
    private CacheService cacheService;

    @Override
    public void sendSmsToMQ(List<Standard_Submit> listSubmit) {
        for (Standard_Submit standardSubmit : listSubmit) {
            smsSender.sendMessage(RabbitMqConsants.TOPIC_PRE_SEND, standardSubmit);
        }
    }

    @Override
    public void pushStatusReport(Standard_Report report) {
        CloseableHttpResponse response = null;
        String json = null;
        report.setSendCount(0);
        //推送失败就重复推送
        while (report.getSendCount() < 3 && (response == null || response.getStatusLine().toString().lastIndexOf("200 ") == -1)){
            //设置发送次数
            report.setSendCount(report.getSendCount() + 1);
            try {
                json = objectMapper.writeValueAsString(report);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            response = sendReport(report, json);
            printSendLog(report,response);
        }
        //3次推送失败就写入队列
        if(report.getSendCount() == 3){
            smsSender.sendMessage(RabbitMqConsants.TOPIC_BAD_REPORT,report);
        }
    }

    private CloseableHttpResponse sendReport(Standard_Report report, String json) {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient client = HttpClientBuilder.create().build();
        //参数
        StringBuffer params = new StringBuffer();
        try {
            params.append("args=" + URLEncoder.encode(json, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //从缓存中通过clientID获取客户URL
        String clientInfoJson = cacheService.getClientInfo(Long.toString(report.getClientID()));
        Map clientMap = null;
        try {
            clientMap = objectMapper.readValue(clientInfoJson, Map.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 创建Get请求
        HttpGet httpGet = new HttpGet(clientMap.get("receiveStatusUrl").toString() + "?" + params);
        //响应模型
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpGet);
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //释放资源
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    private void printSendLog(Standard_Report report, CloseableHttpResponse response) {
        HttpEntity httpEntity = response.getEntity();
        log.error("第" + report.getSendCount() + "次发送响应状态为：{}",response.getStatusLine());
        if (httpEntity != null) {
            log.error("第" + report.getSendCount() + "次发送响应长度：{}",httpEntity.getContentLength());
            try {
                log.error("第" + report.getSendCount() + "次发送响应内容：{}", EntityUtils.toString(httpEntity));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}